import puppeteer from 'puppeteer'
import * as fs from 'node:fs/promises';
import { join } from 'node:path';

const browser = await puppeteer.launch({
    headless: false,//取消无头模式
    defaultViewport: null,
    //全屏打开浏览器
    args: ['--start-maximized'] 
});
const page = await browser.newPage(); //打开一个页面
page.setViewport({ width: 1920, height: 1080 }); //设置页面宽高
await page.goto('https://www.zhipin.com/web/geek/job'); //跳转到后台系统

// 等待页面出现.job-list-box, 验证页面是否加载完成
await page.waitForSelector('.job-list-box', {
    timeout: 10000
})
// await page.click('.city-label', {
//     delay: 500
// })

// await page.click('.city-list-hot li:first-child', {
//     delay: 500
// })

// await page.focus('.search-input-box input')
// await page.keyboard.type('前端', {
//     delay: 200
// })

// await page.click('.search-btn', {
//     delay: 1000
// })

const totalPage = await page.$eval('.options-pages a:nth-last-child(2)', (e) => {
    return parseInt(e.textContent)
})

const allJobs = []
for (let i = 1; i <= totalPage; i++) {
    await page.goto(`https://www.zhipin.com/web/geek/job?query=前端&city=100010000&page=${i}`);
    await page.waitForSelector('.job-list-box', {
        timeout: 10000
    })
    const jobs = await page.$eval('.job-list-box', (e) => {
        return [...e.querySelectorAll('.job-card-wrapper')].map(item => {
            return {
                job: {
                    name: item.querySelector('.job-name').textContent,
                    area: item.querySelector('.job-area').textContent,
                    salary: item.querySelector('.salary').textContent,
                    link: item.querySelector('a.job-card-left').href,
                },
                company: {
                    name: item.querySelector('.company-name').textContent,
                    link: item.querySelector('.company-name a').href,
                }
            }
        })
    })
    allJobs.push(...jobs)
}
// 爬取详情页面
for(let i = 0; i< allJobs.length; i ++) {
    await page.goto(allJobs[i].job.link);

    try{
        await page.waitForSelector('.job-sec-text');

        const jd= await page.$eval('.job-sec-text', el => {
            return el.textContent
        });
        allJobs[i].job.desc = jd;

        console.log(allJobs[i]);
    } catch(e) {}
}

// process.cwd()获取项目的地址 C:\webProgram\study\native-code
// import.meta.dirname 获取当前文件所在目录地址 C:\webProgram\study\native-code\node\puppeteerBoss
console.log(process.cwd(), import.meta.dirname)
fs.writeFile(join(import.meta.dirname, 'jobs.json'), JSON.stringify(allJobs))



// console.log(alljobs)